<template>
  <!-- 电压分布统计 -->
  <div class="chartContent">
    <a-form :model="form" layout="inline" ref="formRef" class="chartForm">
      <a-form-item label="日期" name="code">
        <a-date-picker
          v-model:value="form.date"
          placeholder="选择日期"
          class="formSelect"
          formatter="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          :allowClear="false"
        />
      </a-form-item>
      <a-form-item label="显示维度" name="name">
        <a-select
          ref="select"
          v-model:value="chartType"
          class="formSelect"
          placeholder="请选择"
          @change="changeChartType"
          style="width: 120px"
        >
          <a-select-option
            v-for="item in chartTypeList"
            :value="item.value"
            :key="item.value"
          >
            {{ item.label }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="电池堆">
        <a-select
          ref="select"
          v-model:value="form.linkId"
          class="formInput"
          allow-clear
          placeholder="请选择"
          :disabled="chartType === 3"
          @change="changeLink"
        >
          <a-select-option
            v-for="item in energyLinkList"
            :value="item.deviceId"
            :key="item.deviceId"
          >
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="电池簇">
        <a-select
          ref="select"
          v-model:value="form.equipId"
          class="formInput"
          allow-clear
          placeholder="请选择"
          :disabled="chartType !== 1"
        >
          <a-select-option
            v-for="item in blockList"
            :value="item.deviceId"
            :key="item.deviceId"
          >
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-button
        type="primary"
        class="filterBtn"
        @click="handleFilter"
        :loading="chartLoading"
        >查询</a-button
      >
      <a-button
        v-if="chartType === 1"
        type="primary"
        class="filterBtn yellowBtn"
        @click="checkData"
        >查看数据</a-button
      >
    </a-form>
    <a-spin :spinning="chartLoading">
      <div
        class="chartContainer"
        ref="voltageChartRef"
        v-show="chartType"
      ></div>
    </a-spin>
  </div>
  <!-- 查看数据 -->
  <DetailsData
    :detailsDataVisible="detailsDataVisible"
    :chartsTableData="chartsTableData"
    :chartType="chartType"
    :deviceName="currentDeviceName"
    @update:detailsDataVisible="(val) => (detailsDataVisible = val)"
  />
</template>
<script setup>
;
import { commonConfigStore } from "@/stores/commonConfig";
import DetailsData from "./detailsData.vue";
import * as echarts from "echarts";
import { getVoltageDistributionOption } from "./chartOption";
import { getCurrentDate, getYesterdayFromDate } from "@/utils/common";

import { cloneDeep } from "lodash-es";
const props = defineProps({
  stationInfo: {
    type: Number,
  },
});
const $api = inject("$api");
const form = ref({
  date: null,
  linkId: null,
  equipId: null,
});
const chartType = ref(null);
const voltageChartRef = ref(null);
const voltageChart = ref(null);
const chartsData = ref([]);
const energyLinkList = ref([]);
const blockList = ref([]);
const chartLoading = ref(false);
const detailsDataVisible = ref(false);
const chartsTableData = ref([]);
const currentDeviceName = ref("");

const chartTypeList = ref([
  {
    value: 1,
    label: "电池簇",
  },
  {
    value: 2,
    label: "电池堆",
  },
  {
    value: 3,
    label: "电站",
  },
]);

onUnmounted(() => {
  if (voltageChart.value) {
    voltageChart.value.dispose();
  }
  window.removeEventListener("resize", handleResize);
});

// 窗口大小变化处理
const handleResize = () => {
  if (voltageChart.value) {
    voltageChart.value.resize();
  }
};

// 强制重新调整图表尺寸
const forceResizeChart = () => {
  if (voltageChart.value) {
    nextTick(() => {
      setTimeout(() => {
        voltageChart.value.resize();
      }, 100);
    });
  }
};

// 监听窗口大小变化
watch(
  () => voltageChart.value,
  (newChart) => {
    if (newChart) {
      window.addEventListener("resize", handleResize);
    }
  }
);

// 初始化图表
const initChart = () => {
  if (!voltageChartRef.value) {
    console.warn("图表容器DOM元素不存在");
    return;
  }

  const chartInstance = echarts.init(voltageChartRef.value);
  if (chartInstance) {
    chartInstance.clear();
    const option = getVoltageDistributionOption(chartType.value || 1);
    chartInstance.setOption(option);
    voltageChart.value = markRaw(chartInstance);

    // 延迟调用resize确保容器尺寸已确定
    nextTick(() => {
      setTimeout(() => {
        if (voltageChart.value) {
          voltageChart.value.resize();
        }
      }, 100);
    });
  }
};
// 切换电池堆
const changeLink = async (id) => {
  form.value.equipId = null;
  getBlockList(id);
};
const getBlockList = async (id) => {
  const params = {
    stationId: props.stationInfo.id,
    linkId: id,
  };
  const res = await $api.powerBlockList(params);
  if (res && res.code === 0) {
    blockList.value = res.data;
    if (chartType.value === 1) {
      form.value.equipId = blockList.value?.[0]?.deviceId;
    }
  }
};
const changeChartType = async () => {
  form.value.linkId = null;
  form.value.equipId = null;
  switch (chartType.value) {
    case 1:
      // 如果是电池簇
      form.value.linkId = energyLinkList.value?.[0]?.deviceId;
      await getBlockList(form.value.linkId);
      form.value.equipId = blockList.value?.[0]?.deviceId;
      break;
    case 2:
      // 如果是电池堆
      form.value.linkId = energyLinkList.value?.[0]?.deviceId;
  }
};
// 获取电压数据
const getVoltageData = async () => {
  if (!form.value.date) {
    message.warning("请选择日期");
    return;
  }
  if (!chartType.value) {
    message.error("请选择维度");
    return;
  }
  switch (chartType.value) {
    case 1:
      // 如果是电池簇
      if (!form.value.equipId) {
        message.error("请选择电池簇");
        return;
      }
    case 2:
      // 如果是电池堆
      if (!form.value.linkId) {
        message.error("请选择电池堆");
        return;
      }
  }
  chartLoading.value = true;

  const baseParams = {
    stationId: props.stationInfo.id,
    dimensionType: chartType.value,
    date: form.value.date,
  };

  if (chartType.value === 1) {
    // 如果是电池簇
    baseParams.componentId = form.value.equipId;
    await getVoltageScope();
  } else if (chartType.value === 2) {
    // 如果是电池堆
    baseParams.componentId = form.value.linkId;
  }
  // 请求最高电压和最低电压数据
  const [maxVoltageRes, minVoltageRes] = await Promise.all([
    $api.voltageData({ ...baseParams, lineType: 2 }), // 最高电压
    $api.voltageData({ ...baseParams, lineType: 1 }), // 最低电压
  ]);
  if (
    maxVoltageRes &&
    maxVoltageRes.code === 0 &&
    minVoltageRes &&
    minVoltageRes.code === 0
  ) {
    const maxVoltageData = maxVoltageRes.data;
    const minVoltageData = minVoltageRes.data;

    // 合并数据
    const mergedData = mergeVoltageData(maxVoltageData, minVoltageData);
    if (mergedData.tableData && mergedData.tableData.length > 0) {
      updateChart(mergedData);
      // 保存数据用于"查看数据"功能
      chartsData.value = mergedData.tableData || [];
    } else {
      message.warning("当前时间段暂无数据");
      // 清空图表
      chartsData.value = [];
      if (voltageChart.value) {
        voltageChart.value.clear();
      }
    }
  }
  chartLoading.value = false;
};

// 合并电压数据（优化版）
const mergeVoltageData = (maxVoltageData, minVoltageData) => {
  const voltageByTime = {};
  
  // 处理数据的通用函数
  const processVoltageData = (data, type) => {
    if (!data) return;
    
    data.forEach(item => {
      if (!item.lineData) return;
      
      item.lineData.forEach(dp => {
        if (!dp.dateTime) return;
        
        const time = dp.dateTime.substring(11, 16);
        const value = parseFloat(dp.value);
        if (isNaN(value)) return;
        
        if (!voltageByTime[time]) {
          voltageByTime[time] = {};
        }
        
        if (type === 'max') {
          if (!voltageByTime[time].max || value > voltageByTime[time].max.value) {
            voltageByTime[time].max = {
              value,
              linkName: item.linkName || '',
              blockName: item.blockName || ''
            };
          }
        } else if (type === 'min') {
          if (!voltageByTime[time].min || value < voltageByTime[time].min.value) {
            voltageByTime[time].min = {
              value,
              linkName: item.linkName || '',
              blockName: item.blockName || ''
            };
          }
        }
      });
    });
  };
  
  // 处理最高和最低电压数据
  processVoltageData(maxVoltageData, 'max');
  processVoltageData(minVoltageData, 'min');
  
  // 生成排序的时间数组
  const sortedTimes = Object.keys(voltageByTime).sort();
  
  // 构建最终数据
  const chartData = {
    timeData: [],
    maxVoltageData: [],
    minVoltageData: [],
    diffData: []
  };
  const tableData = [];
  const tooltipData = {};
  
  sortedTimes.forEach(time => {
    const timeData = voltageByTime[time];
    const maxV = timeData.max?.value || 0;
    const minV = timeData.min?.value || 0;
    const diff = Math.abs(maxV - minV);
    
    chartData.timeData.push(time);
    chartData.maxVoltageData.push(maxV);
    chartData.minVoltageData.push(minV);
    chartData.diffData.push(diff);
    
    tableData.push({
      time,
      maxVoltage: maxV,
      minVoltage: minV,
      diff,
      maxVoltageBlockName: timeData.max?.blockName || '',
      minVoltageBlockName: timeData.min?.blockName || ''
    });
    
    tooltipData[time] = {
      max: timeData.max || { value: 0, linkName: '', blockName: '' },
      min: timeData.min || { value: 0, linkName: '', blockName: '' }
    };
  });  
  return {
    chartData,
    tableData,
    tooltipData
  };
};

// 更新图表
const updateChart = (data) => {
  if (!voltageChart.value) {
    initChart();
    if (!voltageChart.value) return;
  }

  const chartData = data?.chartData || {
    timeData: [],
    maxVoltageData: [],
    minVoltageData: [],
    diffData: []
  };

  const tooltipData = data?.tooltipData || {};

  const option = getVoltageDistributionOption(chartType.value, tooltipData);

  if (option.xAxis && option.xAxis.data) {
    option.xAxis.data = chartData.timeData;
  }

  if (option.series && option.series.length >= 3) {
    option.series[0].data = chartData.maxVoltageData; // 最高电压
    option.series[1].data = chartData.minVoltageData; // 最低电压
    option.series[2].data = chartData.diffData; // 最大压差
  }

  // 动态设置Y轴最小值
  if (
    chartData.maxVoltageData.length > 0 &&
    chartData.minVoltageData.length > 0
  ) {
    // 获取电压数据的最小值
    const allVoltageData = [
      ...chartData.maxVoltageData,
      ...chartData.minVoltageData,
    ];
    const minVoltage = Math.min(...allVoltageData.filter((v) => v > 0)); // 过滤掉0值

    // 计算Y轴最小值，留10%的空间
    const voltageRange = Math.max(...allVoltageData) - minVoltage;
    const yAxisMin = Math.max(0, minVoltage - voltageRange * 0.1);

    // 设置第一个Y轴的最小值（电压轴）
    if (option.yAxis && Array.isArray(option.yAxis)) {
      option.yAxis[0].min = Math.floor(yAxisMin);
      // 电压差值轴保持从0开始
      option.yAxis[1].min = 0;
    }
  }

  const markAreaData = [];

  // 只有电池簇维度（chartType === 1）才显示充放电时间段
  if (chartType.value === 1) {
    // 提取时间部分的函数（从 "2025-07-10 00:01:00" 提取 "00:01"）
    const extractTime = (dateTimeStr) => {
      const time = dateTimeStr.split(" ")[1];
      return time.substring(0, 5);
    };

    // 添加充电时间段
    if (timeRange.value && timeRange.value.chargeTimes) {
      timeRange.value.chargeTimes.forEach((chargeTime) => {
        // 计算时间区间长度（小时）
        const beginTime = new Date(chargeTime.beginTime);
        const endTime = new Date(chargeTime.endTime);
        const timeDiffHours = (endTime - beginTime) / (1000 * 60 * 60);
        // 只有当时间区间大于1小时时才显示"充电"字样
        const displayName = timeDiffHours > 1 ? "充电" : "";
        markAreaData.push([
          {
            name: displayName,
            xAxis: extractTime(chargeTime.beginTime),
            itemStyle: {
              color: "rgba(217, 0, 27, 0.09)",
              borderColor: "rgba(139, 69, 19, 0.6)",
              borderWidth: 1,
            },
          },
          {
            xAxis: extractTime(chargeTime.endTime),
          },
        ]);
      });
    }

    // 添加放电时间段
    if (timeRange.value && timeRange.value.dischargeTimes) {
      timeRange.value.dischargeTimes.forEach((dischargeTime) => {
        // 计算时间区间长度（小时）
        const beginTime = new Date(dischargeTime.beginTime);
        const endTime = new Date(dischargeTime.endTime);
        const timeDiffHours = (endTime - beginTime) / (1000 * 60 * 60);
        // 只有当时间区间大于1小时时才显示"放电"字样
        const displayName = timeDiffHours > 1 ? "放电" : "";
        markAreaData.push([
          {
            name: displayName,
            xAxis: extractTime(dischargeTime.beginTime),
            itemStyle: {
              color: "rgba(91, 143, 249, 0.09)",
              borderColor: "rgba(25, 25, 112, 0.6)",
              borderWidth: 1,
            },
          },
          {
            xAxis: extractTime(dischargeTime.endTime),
          },
        ]);
      });
    }
  }

  const arr = [0, 2]; // 0 最高电压 1 最低电压 2 电压差值，这里只需要设置最高电压和差值的区间就行
  arr.forEach((item) => {
    option.series[item].markArea = {
      silent: true,
      label: {
        show: true,
        color: "#ffffff",
        fontSize: 12,
        fontWeight: "bold",
        textShadowColor: "rgba(0,0,0,0.8)",
        textShadowBlur: 2,
        textShadowOffsetX: 1,
        textShadowOffsetY: 1,
      },
      itemStyle: {
        color: "rgba(139, 69, 19, 0.2)",
        borderColor: "rgba(139, 69, 19, 0.6)",
        borderWidth: 1,
      },
      data: markAreaData,
    };
  });
  // 使用notMerge参数确保完整更新
  voltageChart.value.setOption(option, true);
};

// 查看数据
const checkData = () => {
  if (!chartsData.value || chartsData.value.length === 0) {
    message.warning("暂无数据");
    return;
  }
  // 获取当前选中的设备名称
  let deviceName = blockList.value.find(
    (item) => item.deviceId === form.value.equipId
  ).name;
  currentDeviceName.value = deviceName;
  chartsTableData.value = chartsData.value;
  detailsDataVisible.value = true;
};

const getEnergyLinkList = async () => {
  // 获取电池堆列表 如果不是主电池堆，需要拉取电池堆列表指定所属
  const res = await $api.energyLinkList({
    current: 1,
    size: 10000,
    stationId: props.stationInfo.id,
  });
  energyLinkList.value = res?.data;
};

const getVoltDimension = async () => {
  const res = await $api.voltDimension({
    stationId: props.stationInfo.id,
  });
  if (res?.code === 0) {
    chartTypeList.value = chartTypeList.value.filter((item) =>
      res.data.includes(item.value)
    );
    chartType.value = chartTypeList.value[0].value;
    await changeChartType(); // 处理维度、电池堆、电池簇联动
    getVoltageData();
  }
};

const timeRange = ref([]);
const getVoltageScope = async () => {
  const params = {
    stationId: props.stationInfo.id,
    blockId: form.value.equipId,
    date: form.value.date,
  };
  const res = await $api.voltageScope(params);
  if (res && res.code === 0) {
    timeRange.value = res.data;
  }
};

const handleChageStation = async () => {
  form.value.date = getCurrentDate();
  chartType.value = 1; // 默认选择电池簇
  await getEnergyLinkList();
  await getVoltDimension();
};

const handleFilter = async () => {
  await getVoltageData();
};

defineExpose({ handleChageStation, forceResizeChart });
</script>

<style lang="less" scoped>
.chartForm {
  margin-top: 20px;
}
.ant-form-item {
  margin-bottom: 20px;
}
.formInput {
  width: 180px;
}
.chartContainer {
  margin-bottom: 20px;
  width: 100%;
  height: 500px;
  background: #141414;
  border-radius: 4px;
}
.filterBtn {
  margin-right: 20px;
}
</style>
